# coding=utf-8
import json
import redis

from core.m_logging import logger


class RedisOutput(object):
    def __init__(self, connection_string="127.0.0.1", port=6379, db=0):
        self.connection_string = connection_string
        logger.info("connecting to redis %s:%s... db: %s..." % (connection_string, port, db))
        self.r = redis.Redis(host=connection_string, port=port, db=db)

    def output(self, content):
        logger.info('output file to redis %s...' % self.connection_string)
        if "ansiList" in content:
            for asin in content["ansiList"]:
                if self.r.exists("pt:asin:" + asin["asin"]) == 0:
                    i = {"asin": asin["asin"], "summary_url": asin["product_summary_url"], "review_url": asin["review_url"]}
                    logger.info("setting redis key: %s..." % i["asin"])
                    self.r.set("pt:asin:" + i["asin"], json.dumps(i))
                    logger.info("publish redis queue: %s..." % i["asin"])
                    # self.r.publish('pt:asin:q:pending', json.dumps(i))
                    product_summary = {"asin": asin["asin"], "product_summary": asin["product_summary_url"]}
                    customer_review = {"asin": asin["asin"], "customer_review": asin["review_url"]}
                    product_qa = {"asin": asin["asin"], "qa_url": RedisOutput._get_qa_url(asin["asin"])}
                    offer_list = {"asin": asin["asin"], "offer_list_url": RedisOutput._get_offer_list_url(asin["asin"])}
                    self.r.publish("pt:asin:product_summary", json.dumps(product_summary))
                    self.r.publish("pt:asin:customer_review", json.dumps(customer_review))
                    self.r.publish("pt:asin:q_a", json.dumps(product_qa))
                    self.r.publish("pt:asin:offer_list", json.dumps(offer_list))
                else:
                    logger.info('asin exists %s...' % asin["asin"])
        else:
            logger.error("ansiList not in content")

    @staticmethod
    def _get_qa_url(asin):
        qa_url = "https://www.amazon.com/ask/questions/asin/%s/paging/ref=ask_ql_psf_ql_hza" % asin
        return qa_url

    @staticmethod
    def _get_offer_list_url(asin):
        offerList_url = "https://www.amazon.com/gp/offer-listing/%s/" % asin
        return offerList_url
